package com.wzw.shoppingcart.service;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.wzw.shoppingcart.entity.Product;
import com.wzw.shoppingcart.entity.Promotion;
import com.wzw.shoppingcart.mapper.ProductMapper;
import com.wzw.shoppingcart.mapper.PromotionMapper;
import lombok.Setter;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;


/**
 *@author wzw
 * 2023/4/7
 */
@Service
@Setter(onMethod_ = {@Autowired})
public class ProductService extends ServiceImpl<ProductMapper, Product> {

    private PromotionMapper promotionMapper;

    public Product getProductById(Integer productId) {
        return lambdaQuery()
                .eq(Product::getProductId, productId)
                .one();
    }

    public void setDiscountType(List<Product> productList){
        List<Integer> productIds = productList.stream()
                .map(Product::getProductId)
                .collect(Collectors.toList());

        QueryWrapper<Promotion> queryWrapper = new QueryWrapper<>();
        queryWrapper.in("product_id",productIds);
        if (productIds.isEmpty()){
            return;
        }
        List<Promotion> promotions = promotionMapper.selectList(queryWrapper);

        Map<Integer, List<String>> productIdDiscounts = promotions.stream()
                .collect(Collectors.groupingBy(Promotion::getProductId,
                        Collectors.mapping(Promotion::getDiscountType, Collectors.toList())));

        productList.forEach(p->p.setDiscountType(productIdDiscounts.get(p.getProductId())));
    }


}
